package ch.creasystem.tennis.web;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ch.creasystem.tennis.playermgmt.entities.Player;
import ch.creasystem.tennis.playermgmt.facade.PlayerMgmtService;

/**
 * Servlet implementation class TennisServlet
 */
public class TennisServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * EJB Injection of the PlayerSession Bean
	 */
	@EJB
	PlayerMgmtService playerBean;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public TennisServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		// create a new user
		if ("create".equals(action)) {
			try {
			String firstname=request.getParameter("firstname");
			String lastname=request.getParameter("lastname");
			SimpleDateFormat dateFormat = new SimpleDateFormat("DD-MM-yyyy");
			Date date = dateFormat.parse(request.getParameter("birthdate"));
			
			playerBean.createPlayer(firstname, lastname, date);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// delete an existing player
		if ("delete".equals(action)) {
			Long id = Long.parseLong(request.getParameter("id"));
			playerBean.deletePlayer(id);
		}

		// list all player and set the list as request attribute
		List<Player> players = playerBean.getAllPlayers();
		request.setAttribute("playerlist", players);
		RequestDispatcher dispatcher =  request.getRequestDispatcher("tennis/playerlist.jsp");
		dispatcher.forward(request, response);
	}

}
